package com.wzdigit.wms.basic.service.code;

import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.wzdigit.mes.basic.api.BasicDataItemDetailApi;
import com.wzdigit.mes.basic.dto.DataItemDetailDTO;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.core.io.FileSystemResource;
import lombok.extern.slf4j.Slf4j;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import javax.annotation.PostConstruct;
import javax.mail.internet.MimeMessage;

/**
 * 邮件服务
 * 
 * @author Administrator
 *
 */
@Service
@Slf4j
public class IMailCoreService {

    @Autowired
    private SpringBeanCoreService springBeanCoreService;
    
    @Reference(version = "${dubbo.consumers.basic.data.item.detail.api:1.0.0}", check = false, timeout = 300000)
    private BasicDataItemDetailApi dataItemDetailApi;
    
    private static final String BEANNAME = "mailSender";									// 邮件服务bean
    private static final String JAVA_MAIL_PROPERTIES = "javaMailProperties";				// 邮件服务辅配置KEY
    
    private static final String WMS_MAIL_MAIN_CONFIG = "WMS_MAIL_MAIN_CONFIG";				// 邮件服务主配置
    private static final String WMS_MAIL_AUXILIARY_CONFIG = "WMS_MAIL_AUXILIARY_CONFIG";	// 邮件服务辅配置
    
    /**
     * 初始化
     */
    @PostConstruct
    public void initialize() {
    	try {
    		// 主配置参数
    		List<DataItemDetailDTO> mainData = dataItemDetailApi.getDataItemDetailByCode(WMS_MAIL_MAIN_CONFIG);
    		Map<String, Object> mailSender = new HashMap<>();
    		for (DataItemDetailDTO item : mainData) {
    			mailSender.put(item.getItemName(), item.getItemValue());
			}
    		
    		// 辅配置参数
    		List<DataItemDetailDTO> auxiliaryData = dataItemDetailApi.getDataItemDetailByCode(WMS_MAIL_AUXILIARY_CONFIG);
    		if(auxiliaryData.size() > 0) {
    			Properties properties = new Properties();
    			for (DataItemDetailDTO item : auxiliaryData) {
    				properties.put(item.getItemName(), item.getItemValue());
				}
    			mailSender.put(JAVA_MAIL_PROPERTIES, properties);
    		}
    		
    		// 注册服务
			springBeanCoreService.registerBean(BEANNAME, JavaMailSenderImpl.class, mailSender);
			
			log.info(String.format("邮件服务初始化成功"));
		} catch (Exception e) {
			log.error("邮件服务初始化失败");
			e.printStackTrace();
		}
	}
    
    private JavaMailSenderImpl getMailSender() {
    	return springBeanCoreService.getBean(BEANNAME, JavaMailSenderImpl.class);
    }
    
    /**
     * 简单文本邮件
     * 
     * @param to		收件人
     * @param subject	主题
     * @param content	内容
     * @throws Exception
     */
    public void sendSimpleMail(String to, String subject, String content) throws Exception {
    	try {
    		JavaMailSenderImpl mailSender = getMailSender();
    		//创建SimpleMailMessage对象
    		SimpleMailMessage message = new SimpleMailMessage();
    		//邮件发送人
    		message.setFrom(mailSender.getUsername());
    		//邮件接收人
    		message.setTo(to);
    		//邮件主题
    		message.setSubject(subject);
    		//邮件内容
    		message.setText(content);
    		//发送邮件
    		mailSender.send(message);
    		
    		log.info(String.format("[%s]邮件发送OK。发送人[%s]，接收人[%s]", subject, mailSender.getUsername(), to));
		} catch (Exception e) {
			log.error("发送邮件异常");
            throw e;
		}
    }

    /**
     * html邮件
     * 
     * @param to 		收件人
     * @param subject 	主题
     * @param content 	内容
     * @throws Exception 
     */
    public void sendHtmlMail(String to, String subject, String content) throws Exception {
        try {
        	JavaMailSenderImpl mailSender = getMailSender();
        	//获取MimeMessage对象
        	MimeMessage message = mailSender.createMimeMessage();
        	MimeMessageHelper messageHelper = new MimeMessageHelper(message, true);
            //邮件发送人
            messageHelper.setFrom(mailSender.getUsername());
            //邮件接收人
            messageHelper.setTo(to);
            //邮件主题
            message.setSubject(subject);
            //邮件内容，html格式
            messageHelper.setText(content, true);
            //发送
            mailSender.send(message);

            log.info(String.format("[%s]邮件发送OK。发送人[%s]，接收人[%s]", subject, mailSender.getUsername(), to));
        } catch (Exception e) {
        	log.error("发送邮件异常");
            throw e;
        }
    }

    /**
     * 带附件的邮件
     * 
     * @param to 		收件人
     * @param subject 	主题
     * @param content 	内容
     * @param fileName 	附件名称
     * @param filePath 	附件路径
     * @throws Exception 
     */
    public void sendAttachmentsMail(String to, String subject, String content, String fileName, String filePath) throws Exception {
        try {
        	JavaMailSenderImpl mailSender = getMailSender();
        	MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(mailSender.getUsername());
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);

            FileSystemResource file = new FileSystemResource(new File(filePath));
            helper.addAttachment(fileName, file);
            mailSender.send(message);
            
            log.info(String.format("[%s]邮件发送OK。发送人[%s]，接收人[%s]", subject, mailSender.getUsername(), to));
        } catch (Exception e) {
        	log.error("发送邮件异常");
            throw e;
        }
    }
    
    /**
     * 带附件的邮件
     * 
     * @param to		收件人
     * @param subject	主题
     * @param content	内容
     * @param fileMap
     * @throws Exception
     */
    public void sendAttachmentsMail(String to, String subject, String content, Map<String, String> fileMap) throws Exception {
        try {
        	JavaMailSenderImpl mailSender = getMailSender();
        	MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(mailSender.getUsername());
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);

            for (String fileName : fileMap.keySet()) {
            	FileSystemResource file = new FileSystemResource(new File(fileMap.get(fileName)));
            	helper.addAttachment(fileName, file);
			}
            mailSender.send(message);
            
            log.info(String.format("[%s]邮件发送OK。发送人[%s]，接收人[%s]", subject, mailSender.getUsername(), to));
        } catch (Exception e) {
        	log.error("发送邮件异常");
            throw e;
        }
    }
}
